package com.javatest.ajax.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2018/8/15 17:09
 */
public class EncodingFilter extends AbstractHttpFilter {
    private static final Logger LOGGER = LoggerFactory.getLogger(EncodingFilter.class);
    private String encoding;

    @Override
    protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        LOGGER.debug("set request encoding...");
        // 字符编码过滤器，可以防止中文乱码
        // 一般设置为全部地址“/*”
        request.setCharacterEncoding(encoding);
        chain.doFilter(request, response);
    }

    @Override
    protected void init() {
        encoding = getFilterConfig().getServletContext().getInitParameter("encoding");
    }
}
